package com.energyfuture.system.controller;

import com.energyfuture.common.core.constant.CacheConstants;
import com.energyfuture.common.core.constant.HttpStatus;
import com.energyfuture.common.core.exception.BaseException;
import com.energyfuture.common.core.utils.StringUtils;
import com.energyfuture.common.core.utils.sql.SqlUtil;
import com.energyfuture.common.core.web.controller.BaseController;
import com.energyfuture.common.core.web.domain.AjaxResult;
import com.energyfuture.common.core.web.page.PageDomain;
import com.energyfuture.common.core.web.page.TableDataInfo;
import com.energyfuture.common.core.web.page.TableSupport;
import com.energyfuture.common.log.annotation.Log;
import com.energyfuture.common.log.enums.BusinessType;
import com.energyfuture.system.api.RemoteLogService;
import com.energyfuture.system.api.model.SegmentEntity;
import com.energyfuture.system.api.model.SysparaEntity;
import com.energyfuture.system.service.ISysParamService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 系统参数管理
 *
 * @author energyfuture
 */
@RestController
@RequestMapping("/param")
public class SysParamController extends BaseController {
    @Autowired
    private ISysParamService paramService;

    @Autowired
    RemoteLogService remoteLogService;


    @GetMapping("/ipList")
    public TableDataInfo ipList(SegmentEntity segmentEntity) {
        startPage();
        List<SegmentEntity> list = paramService.ipList(segmentEntity);
        return getDataTable(list);
    }

    @GetMapping("/ipQuery")
    public AjaxResult ipQuery(@RequestParam("id") String id) {
        return AjaxResult.success(paramService.selectIpById(id));
    }

    @DeleteMapping("/ipDelete")
    public AjaxResult ipDelete(@RequestBody Map<String,List<String>> ids) {
        int result = paramService.ipDelete(ids.get("ids"));
        if (result > 0) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    @PostMapping("/ipUpdate")
    public AjaxResult ipUpdate(@RequestBody SegmentEntity segmentEntity) {
        int result = paramService.ipUpdate(segmentEntity);
        if (result == 1) {
            return AjaxResult.success("修改成功");
        } else {
            return AjaxResult.error("修改失败");
        }
    }

    @PostMapping("/ipInsert")
    public AjaxResult ipInsert(@RequestBody SegmentEntity segmentEntity) {
        int result = paramService.ipInsert(segmentEntity);
        if (result == 1) {
            return AjaxResult.success("新增成功");
        } else {
            return AjaxResult.error("新增失败");
        }
    }

    @GetMapping("/selectParam")
    public AjaxResult selectParam() {
        return AjaxResult.success(paramService.selectParam());
    }

    @Log(title = "修改系统参数", businessType = BusinessType.UPDATE)
    @PostMapping("/updateSysparam")
    public AjaxResult updateSysparam(@RequestBody SysparaEntity sysparaEntity) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            int result = 0;
            String rexp = "^(?:(?:[0-2][0-3])|(?:[0-1][0-9])):[0-5][0-9]$";
            Pattern pat = Pattern.compile(rexp);
            if (sysparaEntity.getXtfwjssj() != null && !sysparaEntity.getXtfwjssj().equals("") && sysparaEntity.getXtfwqssj() != null && !sysparaEntity.getXtfwqssj().equals("")) {
                //正则表达式判断时间格式
                if (pat.matcher(sysparaEntity.getXtfwjssj()).matches() && pat.matcher(sysparaEntity.getXtfwqssj()).matches()) {
                    //判断系统访问结束时间是否大于起始时间，间隔至少为1小时
                    if (compTime(sysparaEntity.getXtfwjssj(), sysparaEntity.getXtfwqssj())) {
                        result = paramService.updateSysparam(sysparaEntity);
                    }
                }

            }


            if (result == 1) {
                return AjaxResult.success("修改成功");
                //修改成功后下次登录生效
                //log = new LogInfoEntityCustom("系统参数修改", "管理员[" + ShiroAuthenticationManager.getUserAccountName() + "]修改系统参数成功", LogResult.SUCCESS, LogType.SYSTEM);
            } else {
                return AjaxResult.error("修改失败");
                //log = new LogInfoEntityCustom("系统参数修改", "管理员[" + ShiroAuthenticationManager.getUserAccountName() + "]修改系统参数成功",  LogResult.FAIL, LogType.SYSTEM);
            }
        } catch (Exception e) {
            throw new BaseException("修改系统参数发生错误, 请联系管理员");
        }
    }

    public boolean compTime(String s1, String s2) {
        try {
            if (s1.indexOf(":") < 0 || s1.indexOf(":") < 0) {
                System.out.println("格式不正确");
            } else {
                String[] array1 = s1.split(":");
                int total1 = Integer.valueOf(array1[0]) * 3600 + Integer.valueOf(array1[1]) * 60;
                String[] array2 = s2.split(":");
                int total2 = Integer.valueOf(array2[0]) * 3600 + Integer.valueOf(array2[1]) * 60;
                return total1 - total2 >= 3600 ? true : false;
            }
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            return false;
        }
        return false;

    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    private String getTokenKey(String token) {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }

}
